package com.qinge.blog.security.filter;

import com.alibaba.fastjson.JSON;
import com.qinge.blog.service.CaptchaService;
import com.qinge.blog.utils.result.JsonResult;
import com.qinge.blog.utils.result.ResultCode;
import com.qinge.blog.utils.result.ResultTool;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author QDW
 * @date 2022/5/5 9:26
 * @description 验证码过滤器
 **/
@Component
public class VerifyCodeFilter extends GenericFilterBean {

    @Resource
    CaptchaService captchaService;

    // 只对/login请求的验证码进行处理
    private String defaultFilterProcessUrl = "/login";

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        if ("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())) {
            JsonResult result = null;

            // 验证码验证
            String UUID = request.getParameter("uuid");
            String code = request.getParameter("code");

            if (StringUtils.isEmpty(code)) {
                result=ResultTool.fail(ResultCode.PARAM_IS_BLANK);
            } else if (!captchaService.versifyCaptcha(UUID, code)) {
                result=ResultTool.fail(ResultCode.VERIFY_FAIL);
            }

            // 如果验证码验证失败，直接返回
            if(result!=null){
                response.setContentType("text/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(result));
                return;
            }

        }

        // 验证码正常或者非验证访问，则直接进行下一步的处理
        chain.doFilter(request, response);

    }

}

